/**
 * 
 */
package com.wubo.sec.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Service;

import com.wubo.sec.bean.MenuAuthRelate;
import com.wubo.sec.config.LangUtil;
import com.wubo.sec.event.AuthorityEvent;
import com.wubo.sec.log.LogHelper;
import com.wubo.sec.log.LogState;
import com.wubo.sec.model.Authority;
import com.wubo.sec.model.Menu;
import com.wubo.sec.service.IMenuAuthService;
import com.wubo.spring.hibernate.BaseHibernateDao;

/**
 * @author wubo
 * @CreateDate 2010-8-9
 * @version 1.0.01
 */
@Service
public class MenuAuthService implements IMenuAuthService, ApplicationListener<ApplicationEvent>  {
	
	private BaseHibernateDao dao;
	
	public BaseHibernateDao getDao() {
		return dao;
	}
	@Autowired
	public void setDao(BaseHibernateDao dao) {
		this.dao = dao;
	}	
	/* (non-Javadoc)
	 * @see com.asc.sf.service.IMenuAuthService#getAuthCodes(java.lang.String)
	 */
	public String getAuthCode(String menuCode) {
		return dao.queryForObject("select a.code from Menu m inner join m.auth a where m.code = ?", new Object[]{menuCode});
	}

	/* (non-Javadoc)
	 * @see com.asc.sf.service.IMenuAuthService#relate(java.lang.String, java.lang.String[])
	 */
	public void relate(MenuAuthRelate relate) {
		String menuCode = relate.getMenuCode();
		String authCode = relate.getAuthCode();
		Menu menu = dao.get(Menu.class, menuCode);
		
		String authName = "";
		if(authCode != null){
			Authority auth = dao.get(Authority.class, authCode);
			
			authName = auth.getName();
			
			menu.setAuth(auth);
		}else{
			menu.setAuth(null);
		}
		
		dao.update(menu);
		
		if(LogState.isLogCode()){
			LogHelper.actionLog(LangUtil.get("RelateMenuAuth"), LangUtil.get("MenuAuthDetail", menuCode+"("+menu.getName()+")", authCode+"("+authName+")"));
		}else{
			LogHelper.actionLog(LangUtil.get("RelateMenuAuth"), LangUtil.get("MenuAuthDetail", menu.getName(), authName));
		}	
	}

	public void onApplicationEvent(ApplicationEvent event) {
		if(event instanceof AuthorityEvent){
			AuthorityEvent authEvent = (AuthorityEvent) event;
			if( authEvent.getType() == AuthorityEvent.DELETE ){
				dao.executeSQL("DELETE FROM SEC_MENU_AUTH WHERE AUTH_REL = ?", authEvent.getEntity().getCode());
			}
		}
	}

}
